﻿using DevExpress.ExpressApp;
using DevExpress.ExpressApp.Actions;
using DevExpress.Persistent.Base;
using EasyXaf.EntityDesigner.BusinessObjects.Entities;
using EasyXaf.EntityDesigner.CodeTemplates;

namespace EasyXaf.EntityDesigner.Controllers;

public class ExportCodeViewController : ObjectViewController<ListView, Entity>
{
    public SimpleAction ExportAction { get; }

    public ExportCodeViewController()
    {
        TargetViewNesting = Nesting.Root;

        ExportAction = new SimpleAction(this, $"{Name}-{nameof(ExportAction)}", PredefinedCategory.View)
        {
            Caption = "导出代码",
            ImageName = "Action_Export",
        };
    }

    protected override void OnActivated()
    {
        base.OnActivated();

        ExportAction.Execute += ExportAction_Execute;
    }

    protected override void OnDeactivated()
    {
        ExportAction.Execute -= ExportAction_Execute;

        base.OnDeactivated();
    }

    private void ExportAction_Execute(object sender, SimpleActionExecuteEventArgs e)
    {
        var objectSpace = Application.CreateObjectSpace(typeof(ExportCodeObject));
        var obj = objectSpace.CreateObject<ExportCodeObject>();
        var view = Application.CreateDetailView(objectSpace, obj);
        Application.ShowViewStrategy.ShowViewInPopupWindow(view, () =>
        {
            if (string.IsNullOrWhiteSpace(obj.Path))
            {
                throw new Exception("路径不能为空");
            }
            View.CollectionSource.List
                .OfType<Entity>().FirstOrDefault()?.DomainModel?
                .ExportCode(obj.Path, obj.GenerateExtensionEntity);
        });
    }
}
